const Router = require("koa-router");
const SMSClient = require("@alicloud/sms-sdk");
const schedule = require("node-schedule");
const { Auth } = require("@middlewares/auth");
const { TextMsg } = require("@models/textmsg");
const { Task } = require("@models/task");
const { Op } = require("sequelize");
const { Admin } = require("@models/admin");
const router = new Router({
  prefix: "/admin/sms",
});

// 创建短信模版
router.post("/create", new Auth().m, async (ctx, next) => {
  const {
    access_key_id,
    secret_access_key,
    sign_name,
    template_code,
    template_param,
    text_name,
  } = ctx.request.body;

  const textmsg = await TextMsg.create({
    admin_id: ctx.auth.uid,
    text_name,
    access_key_id,
    secret_access_key,
    sign_name,
    template_code,
    template_param,
  });

  if (!textmsg) {
    throw new global.errs.AuthFailed("模版创建失败");
  }

  ctx.body = {
    code: 200,
    msg: "创建成功",
  };
});

// 短信模版列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page, pageSize, text_name } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = text_name ? { text_name: { [Op.like]: `%${text_name}%` } } : {};

  const { count: total, rows } = await TextMsg.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["testmsg_id", "ASC"]], // 排序
    include: [
      {
        model: Admin,
        required: false,
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 删除短信模版
router.post("/delete", new Auth().m, async (ctx, next) => {
  const { testmsg_id } = ctx.request.body;

  const textmsg = await TextMsg.destroy({
    where: {
      testmsg_id,
    },
    force: true,
  });

  if (!textmsg) {
    throw new global.errs.AuthFailed("模版删除失败");
  }

  ctx.body = {
    code: 200,
    msg: "删除成功",
  };
});

// 更新短信模版
router.post("/update", new Auth().m, async (ctx, next) => {
  const {
    testmsg_id,
    access_key_id,
    secret_access_key,
    sign_name,
    template_code,
    template_param,
    text_name,
  } = ctx.request.body;

  const textmsg = await TextMsg.update(
    {
      access_key_id,
      secret_access_key,
      sign_name,
      template_code,
      template_param,
      text_name,
      admin_id: ctx.auth.uid,
    },
    {
      where: {
        testmsg_id,
      },
    }
  );

  if (textmsg[0] == 0) {
    throw new global.errs.AuthFailed("模版更新失败");
  }

  ctx.body = {
    code: 200,
    msg: "更新成功",
  };
});

// 获取短信模版详情
router.post("/detail", new Auth().m, async (ctx, next) => {
  const { testmsg_id } = ctx.request.body;

  const textmsg = await TextMsg.findOne({
    where: {
      testmsg_id,
    },
  });

  if (!textmsg) {
    throw new global.errs.AuthFailed("模版获取失败");
  }

  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: textmsg,
  };
});

// 发送短信
router.post("/send", new Auth().m, async (ctx, next) => {
  const { send_time, describe, task_name } = ctx.request.body;
  const body = ctx.request.body;
  // 发送短信
  const send_msg = async (body) => {
    const smsClient = new SMSClient({
      accessKeyId: body.access_key_id,
      secretAccessKey: body.secret_access_key,
    });
    const sms = await smsClient.sendSMS({
      PhoneNumbers: body.phone,
      SignName: body.sign_name,
      TemplateCode: body.template_code,
      TemplateParam: body.template_param,
    });
    return sms;
  };
  const admin_id = ctx.auth.uid;
  if (send_time) {
    const task = await Task.create({
      send_time,
      admin_id,
      task_name,
      describe,
    });
    const job = schedule.scheduleJob(`${task.task_id}`, send_time, () => {
      // 到时间需要执行的方法
      send_msg(body);
      task.destroy({ force: true });
    });

    ctx.body = {
      msg: job ? "定时短信创建成功" : "定时短信创建失败",
      code: 200,
    };
  } else {
    const sms = await send_msg(body);
    ctx.body = {
      code: sms.Code == "OK" ? 200 : 1001,
      msg: sms.Message,
    };
  }
});

// 定时任务列表
router.post("/task/list", new Auth().m, async (ctx, next) => {
  const { page, pageSize, task_name } = ctx.request.body;
  const offset = (page - 1) * pageSize;

  const where = task_name ? { task_name: { [Op.like]: `%${task_name}%` } } : {};

  const { count: total, rows } = await Task.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["task_id", "ASC"]], // 排序
    include: [
      {
        model: Admin,
        required: false,
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "创建成功",
    total,
    data: rows,
  };
});

// 取消定时任务
router.post("/task/cancel", new Auth().m, async (ctx, next) => {
  const { task_id } = ctx.request.body;
  schedule.scheduledJobs[`${task_id}`].cancel();
  const task = await Task.destroy({
    where: { task_id },
    force: true
  });

  if (!task) {
    throw new global.errs.AuthFailed("销毁失败");
  }

  ctx.body = {
    code: 200,
    msg: "取消成功",
  };
});

module.exports = router;
